import { LOGIN_URL, HOME_URL } from "@/config";
import { RootState, useSelector } from "@/redux";
import { useEffect, useState } from "react";
import { useLoaderData, useLocation, useNavigate, Navigate, Link } from "react-router-dom";

interface RouterGuardProps {
  children: React.ReactNode;
}
/**
 * @description: 路由守卫
 * @param props
 * @returns
 */
const RouterGuard: React.FC<RouterGuardProps> = props => {
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const token = useSelector((state: RootState) => state.user.token);
  const isLoginPage = pathname === LOGIN_URL;

  // 如果用户未登录且不在登录页面，则重定向到登录页面
  if (!token && !isLoginPage) return <Navigate to={LOGIN_URL} replace/>;
   // 如果用户已登录且在登录页面，则重定向到主页
  if(token && isLoginPage) return <Navigate to={HOME_URL} replace/>;
  // 正常情况渲染组件
  return props.children;
};

export default RouterGuard;
